package com.rfxj.cordova.locationrecord;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class LocationRecord extends CordovaPlugin {
    public static final String RECEIVER_ACTION = "location_in_background";
    private static final String TAG = "LocationRecord";

    private CallbackContext callbackContext;
    private Context context = null ;
    private AMapLocationClient mLocationClient;
    private int jsonType=1;

    AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    JSONObject jo = aMapLocation.toJson(jsonType);
                    Log.w("定位成功:", jo.toString());
                    callbackContext.success(jo);
                } else {
                    // 错误码对照表 http://lbs.amap.com/api/android-location-sdk/guide/utilities/errorcode/
                    Log.e("定位失败错误码:", aMapLocation.getAdCode());
                    Log.e("定位失败信息:", aMapLocation.getErrorInfo());
                    callbackContext.error(aMapLocation.getErrorCode());
                }
            }
        }
    };


    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);

        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RECEIVER_ACTION);
        this.cordova.getActivity().registerReceiver(locationChangeBroadcastReceiver, intentFilter);

        Context context = this.cordova.getActivity().getApplicationContext();
        mLocationClient = new AMapLocationClient(context);
        mLocationClient.setLocationListener(mLocationListener);
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);// 使用签到定位场景
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); //高精度模式
        mLocationClient.setLocationOption(mLocationOption); // 设置定位参数
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        boolean flag = false;
        String orderId="";
        switch (action) {
        case "getLocation":
            jsonType = args.getInt(0);
            this.getLocation(callbackContext);
            flag = true;
            break;
        case "startRecord":
            orderId = args.getString(0);
            this.startRecord(orderId, callbackContext);
            flag=true;
            break;
        case "finishRecord":
            orderId = args.getString(0);
            this.finishRecord(orderId, callbackContext);
            flag=true;
            break;
        }
        return flag;
    }

    private void getLocation(CallbackContext callbackContext) {
        this.callbackContext = callbackContext;

        // 设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        mLocationClient.stopLocation();
        mLocationClient.startLocation(); // 启动定位
        PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);

        r.setKeepCallback(true);
        callbackContext.sendPluginResult(r);

        Log.i(TAG, "getLocation: ");
    }

    private void startRecord(String orderId, CallbackContext callbackContext) {
        callbackContext.success("startRecord 被调用");
        this.cordova.getActivity().startService(new Intent(this.cordova.getActivity(), LocationService.class));

        Log.i(TAG, "startRecord: " + orderId);
    }

    private void finishRecord(String orderId, CallbackContext callbackContext) {
        callbackContext.success("finishRecord 被调用");

        this.cordova.getActivity().sendBroadcast(Utils.getCloseBrodecastIntent());

        Log.i(TAG, "finishRecord: " + orderId);
    }
    private BroadcastReceiver locationChangeBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(LocationRecord.RECEIVER_ACTION)) {
                String locationResult = intent.getStringExtra("result");
                Log.i(TAG,locationResult);
            }
        }
    };
}
